<template>
	<view class="uni-container">
		<uni-forms ref="form" :model="formData" validateTrigger="bind">
			<uni-forms-item name="name" label-width="100" label="商户名称" required>
				<uni-easyinput placeholder="请输入商户名称" v-model="formData.name"></uni-easyinput>
			</uni-forms-item>
			<uni-forms-item name="logo" label-width="100" label="商户LOGO">
				<!-- <uni-easyinput placeholder="商户LOGO" v-model="formData.logo"></uni-easyinput> -->
				<button @click="chooseLogoImage" size="mini">选择图片</button>
				<progress :percent="percent" show-info stroke-width="3" />
				<image v-if="formData.logo" :src="formData.logo" style="width: 100px; height: 100px;"></image>
			</uni-forms-item>
			<uni-forms-item name="owner_id" label-width="100" label="商户管理员" required>
				<view class="owner-select-wrapper">
					<uni-easyinput v-model="ownerInput" placeholder="请输入管理员用户名" @input="onOwnerInput"
						@focus="onOwnerFocus" @blur="onOwnerBlur" :disabled="false">
					</uni-easyinput>
					<!-- 下拉选项列表 -->
					<view v-if="showOwnerDropdown && filteredOwners.length > 0" class="owner-dropdown">
						<view v-for="owner in filteredOwners" :key="owner._id" class="owner-item"
							@click="selectOwner(owner)">
							<text class="owner-name">{{ owner.username }}</text>
						</view>
					</view>
					<!-- 无匹配结果提示 -->
					<view v-if="showOwnerDropdown && ownerInput && filteredOwners.length === 0" class="no-result">
						<text>未找到匹配的用户</text>
					</view>
				</view>
			</uni-forms-item>
			<uni-forms-item name="email" label="邮　箱">
				<uni-easyinput placeholder="请输入邮箱" v-model="formData.email"></uni-easyinput>
			</uni-forms-item>
			<uni-forms-item name="contact" label="联系人" required>
				<uni-easyinput placeholder="请输入联系人" v-model="formData.contact"></uni-easyinput>
			</uni-forms-item>
			<uni-forms-item name="phone" label="联系电话" label-width="100" required>
				<uni-easyinput placeholder="请输入联系电话" v-model="formData.phone"></uni-easyinput>
			</uni-forms-item>

			<uni-forms-item name="address" label="商户地址" label-width="100" required>
				<uni-easyinput placeholder="请输入商户地址" v-model="formData.address"></uni-easyinput>
			</uni-forms-item>
			<uni-forms-item name="description" label="商户描述">
				<uni-easyinput placeholder="请输入商户描述" v-model="formData.description"></uni-easyinput>
			</uni-forms-item>
			<uni-forms-item name="business_license_number" label="营业执照号码" label-width="120">
				<uni-easyinput placeholder="请输入营业执照号码" v-model="formData.business_license_number"></uni-easyinput>
			</uni-forms-item>
			<uni-forms-item name="chooseLicenseImage" label="营业执照">
				<button @click="chooseImage" size="mini">选择图片</button>
				<progress :percent="percent" show-info stroke-width="3" />
				<image v-if="formData.business_license" :src="formData.business_license"
					style="width: 100px; height: 100px;"></image>
			</uni-forms-item>
			<uni-forms-item name="rating" label="商户评分">
				<uni-rate v-model="formData.rating" :max="5" />
			</uni-forms-item>
			<uni-forms-item name="status" label-width="100" label="商户状态" required>
				<uni-data-checkbox v-model="formData.status"
					:localdata="formOptions.status_localdata"></uni-data-checkbox>
			</uni-forms-item>
			<view class="uni-button-group">
				<button type="primary" class="uni-button" style="width: 100px;" @click="submit">提交</button>
				<navigator open-type="navigateBack" style="margin-left: 15px;">
					<button class="uni-button" style="width: 100px;">返回</button>
				</navigator>
			</view>
		</uni-forms>
	</view>
</template>

<script>
	import {
		validator
	} from '../../js_sdk/validator/intangible_merchant.js';

	const db = uniCloud.database();
	const dbCmd = db.command;
	const dbCollectionName = 'intangible_merchant';

	function getValidator(fields) {
		let result = {}
		for (let key in validator) {
			if (fields.includes(key)) {
				result[key] = validator[key]
			}
		}
		return result
	}



	export default {
		data() {
			let formData = {
				"name": "",
				"logo": "",
				"contact": "",
				"email": "",
				"address": "",
				"business_license": "",
				"business_license_number": "",
				"description": "",
				"phone": "",
				"rating": null,
				"status": 1,
				"owner_id": "" // 新增管理员字段

			}
			return {
				percent: 0, //图片上传进度条
				formData,
				formOptions: {
					"status_localdata": [{
							"text": "关闭",
							"value": 0
						},
						{
							"text": "营业中",
							"value": 1
						}
					]
				},
				rules: {
					...getValidator(Object.keys(formData))
				},
				// 管理员选择相关数据
				ownerInput: '', // 管理员输入框的值
				owners: [], // 所有用户数据
				filteredOwners: [], // 过滤后的用户数据
				showOwnerDropdown: false, // 是否显示下拉框
				ownerSearchTimer: null // 搜索防抖定时器

			}
		},
		onLoad() {
			this.loadOwners()
			// ...existing code...
		},
		onReady() {
			this.$refs.form.setRules(this.rules)
		},
		methods: {
			//确定商户管理员
			loadOwners() {
				db.collection('uni-id-users')
					.field('_id,username')
					.orderBy('username asc')
					.get()
					.then((res) => {
						this.owners = res.result.data
					}).catch((err) => {
						console.error('加载用户数据失败:', err)
					})
			},
			onOwnerInput(value) {
				this.ownerInput = value
				if (this.ownerSearchTimer) {
					clearTimeout(this.ownerSearchTimer)
				}
				this.ownerSearchTimer = setTimeout(() => {
					this.searchOwners(value)
				}, 300)
			},
			onOwnerFocus() {
				if (this.ownerInput) {
					this.searchOwners(this.ownerInput)
				}
				this.showOwnerDropdown = true
			},
			onOwnerBlur() {
				setTimeout(() => {
					this.showOwnerDropdown = false
				}, 200)
			},
			searchOwners(keyword) {
				if (!keyword || keyword.trim() === '') {
					this.filteredOwners = []
					return
				}
				const searchKeyword = keyword.toLowerCase().trim()
				this.filteredOwners = this.owners.filter(owner => {
					return owner.username && owner.username.toLowerCase().includes(searchKeyword)
				}).slice(0, 10)
			},
			selectOwner(owner) {
				this.ownerInput = owner.username
				this.formData.owner_id = owner._id
				this.showOwnerDropdown = false
			},

			//选择图片
			chooseLogoImage() {
				const _self = this
				uniCloud.chooseAndUploadFile({
					type: 'image',
					count: 1,
					onChooseFile(res) {
						return Promise.all(res.tempFiles).then((fileList) => {
							let result = {
								tempFilePaths: []
							}
							result.tempFiles = fileList.map((fileItem, index) => {
								result.tempFilePaths.push(fileItem.path)
								// console.log(222222222222222,fileItem)
								return {
									path: fileItem.path,
									cloudPath: '' + Date.now() + index + '.' + fileItem.name.split(
										'.')[1], // 云端路径，这里随便生成了一个
									fileType: fileItem.fileType
								}
							})
							return result
						})
					},
					onUploadProgress(progressEvent) {
						console.log(progressEvent);
						_self.percent = Math.round((progressEvent.loaded * 100) / progressEvent.total);
					},
					success: async function(res) {
						console.log(res)
						let temp = await uniCloud.getTempFileURL({
							fileList: res.tempFiles.map((item) => item.url)
						});
						// console.log(111111111111,temp,_self.formData)
						_self.formData.logo = temp.fileList[0].tempFileURL
						uni.showToast({
							icon: 'none',
							title: '上传成功',
							duration: 1500
						})
					},
					fail: function(err) {
						console.log(err)
						uni.showToast({
							icon: 'none',
							title: '上传失败',
							duration: 1500
						})
					}
				})
			},
			chooseLicenseImage() {
				const _self = this
				uniCloud.chooseAndUploadFile({
					type: 'image',
					count: 1,
					onChooseFile(res) {
						return Promise.all(res.tempFiles).then((fileList) => {
							let result = {
								tempFilePaths: []
							}
							result.tempFiles = fileList.map((fileItem, index) => {
								result.tempFilePaths.push(fileItem.path)
								// console.log(222222222222222,fileItem)
								return {
									path: fileItem.path,
									cloudPath: '' + Date.now() + index + '.' + fileItem.name.split(
										'.')[1], // 云端路径，这里随便生成了一个
									fileType: fileItem.fileType
								}
							})
							return result
						})
					},
					onUploadProgress(progressEvent) {
						console.log(progressEvent);
						_self.percent = Math.round((progressEvent.loaded * 100) / progressEvent.total);
					},
					success: async function(res) {
						// console.log(res)
						let temp = await uniCloud.getTempFileURL({
							fileList: res.tempFiles.map((item) => item.url)
						});
						// console.log(111111111111,temp)
						_self.formData.business_license = temp.fileList[0].tempFileURL
						uni.showToast({
							icon: 'none',
							title: '上传成功',
							duration: 1500
						})
					},
					fail: function(err) {
						console.log(err)
						uni.showToast({
							icon: 'none',
							title: '上传失败',
							duration: 1500
						})
					}
				})
			},
			/**
			 * 验证表单并提交
			 */
			submit() {
				uni.showLoading({
					mask: true
				})
				this.$refs.form.validate().then((res) => {
					return this.submitForm(res)
				}).catch(() => {}).finally(() => {
					uni.hideLoading()
				})
			},

			/**
			 * 提交表单
			 */
			submitForm(value) {
				// 使用 clientDB 提交数据
				return db.collection(dbCollectionName).add(value).then((res) => {
					uni.showToast({
						title: '新增成功'
					})
					this.getOpenerEventChannel().emit('refreshData')
					setTimeout(() => uni.navigateBack(), 500)
				}).catch((err) => {
					uni.showModal({
						content: err.message || '请求服务失败',
						showCancel: false
					})
				})
			}
		}
	}
</script>
<style lang="scss">
	.owner-select-wrapper {
		position: relative;
		z-index: 99;
	}

	.owner-dropdown {
		position: absolute;
		top: 100%;
		left: 0;
		right: 0;
		background-color: #fff;
		border: 1px solid #ddd;
		border-top: none;
		border-radius: 0 0 6px 6px;
		max-height: 200px;
		overflow-y: auto;
		z-index: 99;
		box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
	}

	.owner-item {
		padding: 12px 16px;
		border-bottom: 1px solid #f5f5f5;
		cursor: pointer;
		transition: background-color 0.2s;

		&:hover {
			background-color: #f8f9fa;
		}

		&:last-child {
			border-bottom: none;
		}

		.owner-name {
			display: block;
			font-size: 14px;
			color: #333;
			font-weight: 500;
			margin-bottom: 4px;
		}
	}

	.no-result {
		padding: 16px;
		text-align: center;
		color: #999;
		font-size: 14px;
	}
</style>